<template>
    <div class="panel">
        <div class="title">
            <span>机构信息</span>
            <span>[当前选择：<span v-html="currentNode.name"></span>]</span>
        </div>
        <div class="search">
            <el-input style="height:38px;" v-model="filterText" clearable @keydown.enter="onSearch"
                placeholder="请输入机构名称进行搜索">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <Search />
                    </el-icon>
                </template>
                <template #append>
                    <el-button @click="onSearch" :icon="Search" />
                </template>
            </el-input>
        </div>
        <div class="tree">
            <el-tree ref="treeRef" highlight-current :default-expand-all="expandAll" :data="treeData" lazy v-loading="loading"
                :expand-on-click-node="false" @node-click="onNodeClick" :load="loadNode" :props="props"
                node-key="id" :filter-node-method="filterNode">
                <template #default="{ node, data }">
                    <!--@dblclick="handleDblClick(data)"-->
                    <div class="custom-tree-node">
                        <span>
                            <SvgIcon :name="data.icon" />
                            <span v-if="data.hightmc" style="margin-left:8px;" v-html="data.hightmc"></span>
                            <span v-else style="margin-left:8px;">{{ node.label }}</span>
                        </span>
                        <!-- <span v-if="node.data.lx != 'county'">
                        <el-button type="primary" link>新增</el-button>
                        <el-button type="danger" link>删除</el-button>
                    </span> -->
                    </div>
                </template>
            </el-tree>
        </div>
        <div class="footer">
            <el-button type="default" :icon="Search" @click="handleViewAddressTree">查看</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup name="OrganTreeSelect">

import { nextTick, ref, reactive, watch } from 'vue'
import { ElTree, ElMessage } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { Search } from "@element-plus/icons-vue";
import { queryTree } from "/@/api/auth/organ";
interface Tree {
    name: string
    icon: string
    leaf?: boolean
}
const expandAll = ref<boolean>(false)
const treeData = ref<any>([]), loading = ref<boolean>(false)

const treeRef = ref<InstanceType<typeof ElTree>>()

/**搜索 */
const filterText = ref<string>('')

watch(filterText, (val) => {
    if (!val) {
        resetNode()
    }
})

/**
 * 
 * @param value 过滤
 * @param data 
 */
const filterNode = (value: string, data:any) => {
    if (!value) return true
    return data.name.includes(value)
}

const currentNode = ref<any>({ name: '未选择' })

/**
 * 搜索地址，需要关闭懒加载
 */
 const onSearch = async () => {
    if (filterText.value) {
        treeRef.value!.store.lazy = false
        const rest = await queryTree({ pid: '', keyword: filterText.value });
        if (rest) {
            const data = rest.data;
            treeData.value = rest.data
            setTimeout(() => {
                treeRef.value!.filter(filterText.value)
                expandAll.value = true;
            }, 50)
        }
    } else {
        resetNode()
    }
}

const emit = defineEmits(['nodeClick'])

const handleViewAddressTree = () => {
    if (!currentNode.value!.id) {
        ElMessage.error('请选择需要编辑的节点信息');
        return;
    }
    emit('nodeClick', currentNode.value)
}

const resetNode = () => {
    expandAll.value = false;
    treeRef.value!.store.lazy = true
    treeData.value = []
    setTimeout(() => {
        loadNode(loadNodeParam.chooseNode, loadNodeParam.treeResolve)
    }, 50)
}

const props = {
    label: 'name',
    children: 'children',
    isLeaf: 'leaf',
}

const onNodeClick = (data:any, node:any) => {
    currentNode.value = data;
    emit('nodeClick', data)
}

//保存load的resolve方法
const loadNodeParam = reactive<any>({
    treeResolve: null,
    chooseNode: {}
})
const loadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
    if (node.level === 0) {
        loadNodeParam.treeResolve = resolve
        loadNodeParam.chooseNode = node
        loading.value = true;
    }
    const da = node.data;
    const param = {pid: da.id}
    const res: any = await queryTree(param);
    loading.value = false;
    if(res && res.code === 0) {
        var data = res.data
        emit('nodeClick', data[0])
        return resolve(data)
    }
}
</script>
<style lang="scss" scoped>
.panel {
    flex-direction: column;
    display: flex;
    width: 100%;
    height: 100%;
}

.title {
    padding-left: 12px;
    padding-right: 12px;
    height: 40px;
    line-height: 40px;
    background-color: #fff;
    font-size: 16px;
    border-bottom: 1px solid #efefef;
    display: flex;
    justify-content: space-between;
}

.search {
    padding: 4px 6px;
    background-color: #fff;
    border-bottom: 1px solid #efefef;
    display: flex;
}

.tree {
    display: flex;
    overflow-y: auto;
    width: 100%;
    height: 0;
    flex: 1 1 auto;
}

.footer {
    border-top: 1px solid #efefef;
    width: 100%;
    padding: 6px 6px;
    background-color: #fff;
}

:deep(.el-tree) {
    width: 100%
}

:deep(.el-tree-node__label) {
    width: 100%;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>